<?php

namespace App\Domain\Menu\Controllers;

use App\Domain\Menu\Models\MenuModel;
use App\Domain\Menu\Requests\createMenuPost;
use App\Domain\Menu\Services\MenuService;
use App\Http\Controllers\Controller;
use App\Supports\Constant\PaginationConst;
use App\Supports\Formatter\ResponseFormatter;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class MenuController extends Controller
{
    //菜单添加
    public function createMenu(createMenuPost $request, MenuService $menuService)
    {
        $param = $request->validated();
        $res = $menuService->create($param);
        return $this->success($res);
    }

    //菜单列表
    public function list(Request $request, MenuService $menuService)
    {
        $this->validate($request, [
            'name' => 'string|nullable',
            'url' => 'string|nullable',
            'sort' => '',
            'pid' => '',
            'currentPage' => 'integer|min:1|nullable',
            'pageSize' => 'integer|min:1|nullable',
        ]);
        $param = [
            'url' => $request['url'],
            'name' => $request['name'],
            'sort' => $request['sort'],
            'pid' => $request['pid'],
            'currentPage' => $request->input('currentPage', 1),
            'pageSize' => $request->input('pageSize', PaginationConst::PAGE_SIZE),
        ];
        $menuPaginator = $menuService->list($param);
        $menuPaginator = new LengthAwarePaginator($menuPaginator->items(), $menuPaginator->total(), $menuPaginator->perPage(), $menuPaginator->currentPage());

        //格式化
        $keyMap = [
            'id' => 'id',
            'name' => 'name',
            'url' => 'url',
            'pid' => 'pid',
            'pName' => 'pName',
            'sort' => 'sort',
        ];
        return $this->success(ResponseFormatter::formatterPaginator($menuPaginator, $keyMap));
    }

    //删除菜单
    public function del(Request $request, MenuService $menuService)
    {
        $res = $menuService->del($request['id']);
        return $this->success($res);
    }

    //修改菜单
    public function updateMenu(Request $request, MenuService $menuService)
    {
        $this->validate($request, [
            'id' => 'required',
            'name' => 'required',
            'url' => 'required',
            'sort' => '',
            'pid' => '',
            'pName' => '',
        ]);
        $param = [
            'id' => $request['id'],
            'name' => $request['name'],
            'url' => $request['url'],
            'pid' => $request['pid'],
            'pName' => $request['pName'],
            'sort' => $request['sort'],
        ];
        $data = $menuService->update($param);
        return $this->success($data);
    }
}
